package cn.hdu.liang.ch02.classpath;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

/**
 * 目录形式的类路径, 参数就是指定的路径
 */
public class DirEntry extends Entry {
    //绝对路径
    private String absDir;

    public DirEntry(String path) {
        File dir = new File(path);
        if(dir.exists()) {
            absDir = dir.getAbsolutePath();
        }
    }

    /**
     * 将class文件转为byte数组格式
     *
     * @param className class文件的相对路径，路径之间用斜线 / 分隔，文件名有.class后缀
     * @return 结果数组
     * @throws IOException
     */
    @Override
    public byte[] readClass(String className) throws IOException {
        File file = new File(absDir, className);
        byte[] temp = new byte[1024];

        ByteArrayOutputStream out;
        try(FileInputStream in = new FileInputStream(file)) {
            out = new ByteArrayOutputStream(1024);

            int size = 0;
            while((size = in.read(temp)) != -1) {
                out.write(temp, 0, size);
            }
        }
        return out.toByteArray();
    }

    @Override
    public String className() {
        return absDir;
    }
}
